package com.wenx.v3system.modular.cloud.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenx.v3core.error.BusinessException;
import com.wenx.v3system.modular.cloud.domain.dto.SysRoleDto;
import com.wenx.v3system.modular.cloud.domain.dto.SysUserDto;
import com.wenx.v3system.modular.cloud.domain.po.SysUserRole;
import com.wenx.v3system.modular.cloud.mapper.SysUserRoleMapper;
import com.wenx.v3system.modular.cloud.service.SysUserRoleService;
import com.wenx.v3system.modular.cloud.service.SysRoleRestService;
import com.wenx.v3system.modular.cloud.service.SysUserRestService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统用户角色关联服务实现类
 * 基于Enhanced RBAC权限模型
 * 提供用户角色关联管理、权限继承和动态授权操作
 * 使用@Lazy注解解决与SysUserRestService的循环依赖问题
 * 
 * @author wenx
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
// @DS(DynamicDataSourceConfig.DEFAULT_DATASOURCE)
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    // 依赖注入
    private final SysRoleRestService sysRoleRestService;
    private final SysUserRestService sysUserRestService;

    // 缓存常量
    private static final String USER_ROLE_CACHE = "sys:user:role";
    private static final String ROLE_USER_CACHE = "sys:role:user";
    private static final String USER_PERMISSIONS_CACHE = "sys:user:permissions";
    private static final String USER_ACTIVE_ROLES_CACHE = "sys:user:active:roles";

    @Override
    @Cacheable(value = USER_ROLE_CACHE, key = "'ids:' + #userId")
    public List<Long> getRoleIdsByUserId(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        
        List<SysUserRole> userRoles = super.list(wrapper);
        return userRoles.stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());
    }

    @Override
    @Cacheable(value = USER_ROLE_CACHE, key = "'roles:' + #userId")
    public List<SysRoleDto> getRolesByUserId(Long userId) {
        List<Long> roleIds = getRoleIdsByUserId(userId);
        if (CollUtil.isEmpty(roleIds)) {
            return Collections.emptyList();
        }
        
        // 通过角色服务获取角色详情
        return roleIds.stream()
                .map(id -> (SysRoleDto) sysRoleRestService.get(id))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    @Override
    @Cacheable(value = ROLE_USER_CACHE, key = "'ids:' + #roleId")
    public List<Long> getUserIdsByRoleId(Long roleId) {
        if (roleId == null) {
            throw new BusinessException("角色ID不能为空");
        }
        
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getRoleId, roleId);
        
        List<SysUserRole> userRoles = super.list(wrapper);
        return userRoles.stream()
                .map(SysUserRole::getUserId)
                .collect(Collectors.toList());
    }

    @Override
    @Cacheable(value = ROLE_USER_CACHE, key = "'users:' + #roleId")
    public List<SysUserDto> getUsersByRoleId(Long roleId) {
        List<Long> userIds = getUserIdsByRoleId(roleId);
        if (CollUtil.isEmpty(userIds)) {
            return Collections.emptyList();
        }
        
        // 通过用户服务获取用户详情
        return userIds.stream()
                .map(id -> (SysUserDto) sysUserRestService.get(id))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {USER_ROLE_CACHE, USER_PERMISSIONS_CACHE, USER_ACTIVE_ROLES_CACHE}, allEntries = true)
    public void assignRolesToUser(Long userId, List<Long> roleIds) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 先删除用户现有角色
        removeUserRoles(userId);
        
        // 批量插入新角色
        if (CollUtil.isNotEmpty(roleIds)) {
            List<SysUserRole> userRoles = roleIds.stream()
                    .map(roleId -> {
                        SysUserRole userRole = new SysUserRole();
                        userRole.setUserId(userId);
                        userRole.setRoleId(roleId);
                        return userRole;
                    })
                    .collect(Collectors.toList());
            
            boolean success = super.saveBatch(userRoles);
            if (!success) {
                throw new BusinessException("用户角色分配失败");
            }
        }
        
        log.info("用户角色分配成功，用户ID: {}, 角色数量: {}", userId, roleIds != null ? roleIds.size() : 0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {USER_ROLE_CACHE, USER_PERMISSIONS_CACHE, USER_ACTIVE_ROLES_CACHE}, allEntries = true)
    public void assignRoleToUser(Long userId, Long roleId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        if (roleId == null) {
            throw new BusinessException("角色ID不能为空");
        }
        
        // 检查是否已存在关联
        if (hasRole(userId, roleId)) {
            return;
        }
        
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        
        boolean success = super.save(userRole);
        if (!success) {
            throw new BusinessException("用户角色分配失败");
        }
        
        log.info("用户角色分配成功，用户ID: {}, 角色ID: {}", userId, roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {USER_ROLE_CACHE, ROLE_USER_CACHE, USER_PERMISSIONS_CACHE, USER_ACTIVE_ROLES_CACHE}, allEntries = true)
    public void removeUserRole(Long userId, Long roleId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        if (roleId == null) {
            throw new BusinessException("角色ID不能为空");
        }
        
        // 使用物理删除避免唯一约束冲突
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId)
               .eq(SysUserRole::getRoleId, roleId);
        
        int deletedCount = baseMapper.delete(wrapper);
        if (deletedCount == 0) {
            log.warn("用户角色关联不存在，用户ID: {}, 角色ID: {}", userId, roleId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {USER_ROLE_CACHE, ROLE_USER_CACHE, USER_PERMISSIONS_CACHE, USER_ACTIVE_ROLES_CACHE}, allEntries = true)
    public void removeUserRoles(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 使用物理删除避免唯一约束冲突
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        
        int deletedCount = baseMapper.delete(wrapper);
        log.info("用户所有角色移除成功，用户ID: {}, 删除记录数: {}", userId, deletedCount);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {USER_ROLE_CACHE, ROLE_USER_CACHE, USER_PERMISSIONS_CACHE, USER_ACTIVE_ROLES_CACHE}, allEntries = true)
    public void removeRoleUsers(Long roleId) {
        if (roleId == null) {
            throw new BusinessException("角色ID不能为空");
        }

        // 使用物理删除避免唯一约束冲突
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getRoleId, roleId);

        int deletedCount = baseMapper.delete(wrapper);
        log.info("角色所有用户关联移除成功，角色ID: {}, 删除记录数: {}", roleId, deletedCount);
    }

    @Override
    public boolean hasRole(Long userId, Long roleId) {
        if (userId == null || roleId == null) {
            return false;
        }
        
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId)
               .eq(SysUserRole::getRoleId, roleId);
        
        return super.count(wrapper) > 0;
    }

    @Override
    public boolean hasRoleByCode(Long userId, String roleCode) {
        if (userId == null || !StringUtils.hasText(roleCode)) {
            return false;
        }
        
        // 获取用户所有角色
        List<SysRoleDto> roles = getRolesByUserId(userId);
        return roles.stream()
                .anyMatch(role -> roleCode.equals(role.getCode()));
    }

    @Override
    public boolean hasAnyRole(Long userId, List<Long> roleIds) {
        if (userId == null || CollUtil.isEmpty(roleIds)) {
            return false;
        }
        
        List<Long> userRoleIds = getRoleIdsByUserId(userId);
        return userRoleIds.stream().anyMatch(roleIds::contains);
    }

    @Override
    public boolean hasAllRoles(Long userId, List<Long> roleIds) {
        if (userId == null || CollUtil.isEmpty(roleIds)) {
            return false;
        }
        
        List<Long> userRoleIds = getRoleIdsByUserId(userId);
        return userRoleIds.containsAll(roleIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {USER_ROLE_CACHE, ROLE_USER_CACHE, USER_PERMISSIONS_CACHE, USER_ACTIVE_ROLES_CACHE}, allEntries = true)
    public void batchAssignRoleToUsers(List<Long> userIds, Long roleId) {
        if (CollUtil.isEmpty(userIds)) {
            throw new BusinessException("用户ID列表不能为空");
        }
        if (roleId == null) {
            throw new BusinessException("角色ID不能为空");
        }
        
        List<SysUserRole> userRoles = userIds.stream()
                .filter(userId -> !hasRole(userId, roleId)) // 过滤已存在的关联
                .map(userId -> {
                    SysUserRole userRole = new SysUserRole();
                    userRole.setUserId(userId);
                    userRole.setRoleId(roleId);
                    return userRole;
                })
                .collect(Collectors.toList());
        
        if (CollUtil.isNotEmpty(userRoles)) {
            boolean success = super.saveBatch(userRoles);
            if (!success) {
                throw new BusinessException("批量用户角色分配失败");
            }
        }
        
        log.info("批量用户角色分配成功，用户数量: {}, 角色ID: {}, 实际分配: {}", 
                userIds.size(), roleId, userRoles.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {USER_ROLE_CACHE, ROLE_USER_CACHE, USER_PERMISSIONS_CACHE, USER_ACTIVE_ROLES_CACHE}, allEntries = true)
    public void batchRemoveUserRole(List<Long> userIds, Long roleId) {
        if (CollUtil.isEmpty(userIds)) {
            throw new BusinessException("用户ID列表不能为空");
        }
        if (roleId == null) {
            throw new BusinessException("角色ID不能为空");
        }
        
        // 使用物理删除避免唯一约束冲突
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SysUserRole::getUserId, userIds)
               .eq(SysUserRole::getRoleId, roleId);
        
        int deletedCount = baseMapper.delete(wrapper);
        log.info("批量用户角色移除成功，用户数量: {}, 角色ID: {}, 删除记录数: {}", userIds.size(), roleId, deletedCount);
    }

    @Override
    @Cacheable(value = USER_ACTIVE_ROLES_CACHE, key = "#userId")
    public List<SysRoleDto> getActiveRolesByUserId(Long userId) {
        List<SysRoleDto> allRoles = getRolesByUserId(userId);
        if (CollUtil.isEmpty(allRoles)) {
            return Collections.emptyList();
        }
        
        // 过滤出状态为启用的角色
        return allRoles.stream()
                .filter(role -> role.getStatus() != null && role.getStatus().getValue() == 1)
                .collect(Collectors.toList());
    }

    @Override
    @Cacheable(value = USER_PERMISSIONS_CACHE, key = "#userId")
    public Set<String> getUserRolePermissions(Long userId) {
        List<SysRoleDto> activeRoles = getActiveRolesByUserId(userId);
        if (CollUtil.isEmpty(activeRoles)) {
            return Collections.emptySet();
        }
        
        // 通过角色获取权限编码集合
        Set<String> permissions = new HashSet<>();
        for (SysRoleDto role : activeRoles) {
            Set<String> rolePermissions = sysRoleRestService.getRolePermissions(role.getId());
            permissions.addAll(rolePermissions);
        }
        
        return permissions;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {USER_ROLE_CACHE, USER_PERMISSIONS_CACHE, USER_ACTIVE_ROLES_CACHE}, allEntries = true)
    public void syncUserRoles(Long userId, List<Long> roleIds) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        // 获取当前用户的角色
        List<Long> currentRoleIds = getRoleIdsByUserId(userId);
        
        // 计算需要添加和删除的角色
        List<Long> toAdd = CollUtil.isEmpty(roleIds) ? Collections.emptyList() : 
                roleIds.stream().filter(roleId -> !currentRoleIds.contains(roleId)).collect(Collectors.toList());
        List<Long> toRemove = currentRoleIds.stream()
                .filter(roleId -> CollUtil.isEmpty(roleIds) || !roleIds.contains(roleId))
                .collect(Collectors.toList());
        
        // 删除不需要的角色
        if (CollUtil.isNotEmpty(toRemove)) {
            for (Long roleId : toRemove) {
                removeUserRole(userId, roleId);
            }
        }
        
        // 添加新角色
        if (CollUtil.isNotEmpty(toAdd)) {
            for (Long roleId : toAdd) {
                assignRoleToUser(userId, roleId);
            }
        }
        
        log.info("用户角色同步成功，用户ID: {}, 添加: {}, 删除: {}", userId, toAdd.size(), toRemove.size());
    }

    @Override
    public long countUsersByRoleId(Long roleId) {
        if (roleId == null) {
            return 0;
        }
        
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getRoleId, roleId);
        
        return super.count(wrapper);
    }

    @Override
    public long countRolesByUserId(Long userId) {
        if (userId == null) {
            return 0;
        }
        
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        
        return super.count(wrapper);
    }
}
